package com.adan.auditlog.handler;

import com.adan.auditlog.entity.DBOperationLog;
import com.adan.auditlog.entity.HandlerParam;
import com.adan.auditlog.entity.SqlCommandType;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 数据库主键Id删除处理器
 *
 * @see com.baomidou.mybatisplus.core.mapper.BaseMapper#deleteById(Serializable)
 */
@Component
@Slf4j
public class AuditDeleteByIdHandler extends AbstractAuditHandler {
    @Override
    public boolean matchMethod(String methodName) {
        return methodName.startsWith(SqlCommandType.DELETE_BY_ID);
    }

    @Override
    public Object doHandle(HandlerParam param, DBOperationLog pLog) throws Throwable {
        Object[] args = param.getProceedingJoinPoint().getArgs();
        Object beforeValue = beforeOperate(args, param.getProxyClass(), pLog);
        pLog.setBeforeValue(JSONObject.toJSONString(beforeValue));
        // 执行sql
        Integer result = (Integer) param.getProceedingJoinPoint().proceed();
        // 执行成功
        if (result > 0) {
            String afterValue = afterOperate(pLog, args);
            pLog.setAfterValue(afterValue);
        }
        sqlLogMapper.insert(pLog);
        return result;
    }
}
